<template>
  <div class="d-flex flex-column vh-100">
    <div class="bg-primary text-white p-3 text-center">
      <h4>{{ room.name }} 聊天室</h4>
      <small>倒计时: {{ countdownText }}</small>
    </div>
    <div class="flex-grow-1 overflow-auto p-3" ref="messagesContainer">
      <ChatMessage v-for="msg in messages" :key="msg.timestamp + msg.from" :msg="msg" :is-me="msg.from === nickname" />
    </div>
    <div class="p-2 border-top d-flex align-items-center">
      <input v-model="inputMessage" @keyup.enter="sendMessage" class="form-control me-2" placeholder="输入消息... 😊" />
      <button class="btn btn-primary" @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import ChatMessage from "../components/ChatMessage.vue";
import axios from "axios";

const messages = ref([]);
const inputMessage = ref("");
const nickname = ref("游客" + Math.floor(Math.random() * 1000));
const countdownText = ref("加载中...");

const roomId = window.location.pathname.split("/").pop();
const room = ref({ name: "" });

let stompClient = null;
let countdownInterval = null;

onMounted(async () => {
  // 获取房间信息
  const res = await axios.get(`/api/rooms/${roomId}`);
  room.value = res.data;

  startCountdown(new Date(room.value.expireAt));

  // 建立 WebSocket
  const socket = new SockJS("/ws");
  stompClient = Stomp.over(socket);
  stompClient.connect({}, () => {
    stompClient.subscribe(`/topic/chat/${roomId}`, msg => {
      messages.value.push(JSON.parse(msg.body));
      scrollToBottom();
    });
  });
});

function sendMessage() {
  if (inputMessage.value.trim() === "") return;
  const msg = { from: nickname.value, content: inputMessage.value };
  stompClient.send(`/app/chat/${roomId}`, {}, JSON.stringify(msg));
  inputMessage.value = "";
}

function scrollToBottom() {
  const container = document.querySelector(".overflow-auto");
  container.scrollTop = container.scrollHeight;
}

function startCountdown(expireAt) {
  countdownInterval = setInterval(() => {
    const diff = new Date(expireAt) - new Date();
    if (diff <= 0) {
      countdownText.value = "房间已解散";
      clearInterval(countdownInterval);
      return;
    }
    const min = Math.floor(diff / 60000);
    const sec = Math.floor((diff % 60000) / 1000);
    countdownText.value = `${min}分${sec}秒`;
  }, 1000);
}
</script>

<style scoped>
.overflow-auto {
  background: #f7f9fc;
}
</style>
